package com.itguigu.process.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itguigu.common.result.Result;
import com.itguigu.model.process.ProcessTemplate;
import com.itguigu.process.service.ProcessTemplateService;
import com.itguigu.process.service.ProcessTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Objects;

/**
 *
 */
@RestController
@Slf4j
@RequestMapping("/admin/process/processTemplate")
@Api(value = "审批模板管理", tags = "审批模板管理")
public class ProcessTemplateController {

    @Resource
    private ProcessTemplateService processTemplateService;


    // 上传流程定义
    @ApiOperation("上传流程定义")
    @PostMapping("/uploadProcessDefinition")
    public Result uploadProcessDefinition(MultipartFile file) throws FileNotFoundException, UnsupportedEncodingException {
        log.info("上传文件 multipartFile");
        // 获取classes目录位置 : 由于存在中文 , 乱码问题
        String pathLuanMa = new File(ResourceUtils.getURL("classpath:").getPath()).getAbsolutePath();
        String path = URLDecoder.decode(pathLuanMa, "utf-8");
        // 设置上传文件夹
        File tempFile = new File(path + "/processes/");
        // 判断是否存在
        if (!tempFile.exists()) {
            tempFile.mkdirs();
        }
        // 创建空文件 , 实现文件写入
        String filename = file.getOriginalFilename();
        File zipFile = new File(path + "/processes/" + filename);
        log.info("zipFile文件的抛出路径 : {}", zipFile);
        // 保持文件到本地
        try {
            file.transferTo(zipFile);
        } catch (IOException e) {
            return Result.error().message("上传失败");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("processDefinitionPath", "processes/" + filename);
        map.put("processDefinitionKey", filename.substring(0, filename.lastIndexOf(".")));
        return Result.success(map);
    }

    // 分页查询审批模板
    @PreAuthorize("hasAuthority('bnt.processTemplate.list')")
    @ApiOperation(value = "获取分页列表")
    @GetMapping("{page}/{limit}")
    public Result index(
            @ApiParam(name = "page", value = "当前页码", required = true)
            @PathVariable Long page,

            @ApiParam(name = "limit", value = "每页记录数", required = true)
            @PathVariable Long limit) {
        Page<ProcessTemplate> pageParam = new Page<>(page, limit);
        IPage<ProcessTemplate> pageModel = processTemplateService.selectPageProcessTemplate(pageParam);
        return Result.success(pageModel);
    }


    @PreAuthorize("hasAuthority('bnt.processTemplate.publish')")
    @ApiOperation(value = "发布")
    @GetMapping("/publish/{id}")
    public Result publish(@PathVariable Long id) {
        log.info("发布模板的id : {}", id);
        processTemplateService.publish(id);
        return Result.success();
    }


    @PreAuthorize("hasAuthority('bnt.processTemplate.templateSet')")
    @ApiOperation(value = "添加template模板")
    @PostMapping("save")
    public Result save(@RequestBody ProcessTemplate processTemplate) {
        log.info("添加的template : {}", processTemplate);
        boolean save = processTemplateService.save(processTemplate);
        return Result.success();
    }

    @PreAuthorize("hasAuthority('bnt.processTemplate.remove')")
    @ApiOperation(value = "删除template")
    @DeleteMapping("remove/{id}")
    public Result remove(@PathVariable Long id) {
        log.info("要删除的流程模板id : {}", id);
        boolean b = processTemplateService.removeById(id);
        return Result.success();
    }

    @PreAuthorize("hasAuthority('bnt.processTemplate.templateSet')")
    @ApiOperation(value = "更新流程模板")
    @PutMapping("update")
    public Result updateById(@RequestBody ProcessTemplate processTemplate) {
        log.info("更新的process template : {}", processTemplate);
        boolean b = processTemplateService.updateById(processTemplate);
        return Result.success();
    }


    @PreAuthorize("hasAuthority('bnt.processTemplate.list')")
    @ApiOperation("根据id获取流程模板")
    @GetMapping("get/{id}")
    public Result get(@PathVariable Long id) {
        log.info("要获取的流程模板的id : {}", id);
        ProcessTemplate processTemplate = processTemplateService.getById(id);
        return Result.success(processTemplate);
    }

}
